<template>
  <div class="sub-category">
      <div class="container">
        <!-- 面包屑 -->
        <SubBread />
        <!-- 筛选区域 -->
        <SubFilter @filterChange="filterChange"/>
        <!-- 商品面板 -->
        <div class="goods-list">
          <!-- 排序 -->
          <SubSort @sortChange="sortChange"/>
          <!-- 商品列表 -->
          <ul>
            <li v-for="item in goodsList" :key="item.id">
              <GoodsItem :goods="item" />
            </li>
          </ul>
          <XtxInfiniteLoading @infinite="getData" :loading="loading" :finished="finished"/>
        </div>
      </div>
  </div>
</template>

<script>
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import GoodsItem from './components/goods-item.vue'
import { ref, watch } from 'vue-demi'
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
export default {
  name: 'SubCategory',
  components: {
    SubBread,
    SubFilter,
    SubSort,
    GoodsItem
  },
  setup () {
    const route = useRoute()
    const loading = ref(false) // 加载中
    const finished = ref(false) // 是否加载完毕
    const goodsList = ref([]) // 商品列表
    let requestParam = {
      page: 1,
      pageSize: 20
    }
    const getData = () => {
      loading.value = true
      // 设置二级分类的id
      requestParam.categoryId = route.params.id
      findSubCategoryGoods(requestParam).then(({ result }) => {
        if (result.items.length) {
          // 有数据就追加数据
          goodsList.value.push(...result.items)
          requestParam.page++
        } else {
          // 没有数据 加载完成
          finished.value = true
        }
        loading.value = false
      })
    }
    // 再更改了二级分类的时候需要重新加载数据
    watch(() => route.params.id, newVal => {
      if (newVal && `/category/sub/${newVal}` === route.path) {
        finished.value = false
        goodsList.value = []
        requestParam = {
          page: 1,
          pageSize: 20
        }
      }
    }, { immediate: true })
    // 更改排序组件的筛选数据，重新请求
    const sortChange = (sortParams) => {
      goodsList.value = []
      if (finished.value) {

      }
      finished.value = false
      requestParam = { ...requestParam, ...sortParams }
      requestParam.page = 1
    }
    // 更改筛选数组的筛选数据，重新请求
    const filterChange = (filterParams) => {
      requestParam = { ...requestParam, ...filterParams }
      requestParam.page = 1
      goodsList.value = []
      finished.value = false
    }
    return { getData, loading, finished, goodsList, sortChange, filterChange }
  }
}
</script>

<style scoped lang="less">
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
   ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
